<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/29
 * Time: 15:44
 */
namespace app\common;

use think\Model;
use think\Request;
use think\Db;

class Modelcon extends Model{
    private $code_msg;
    private $result;
    public function initialize(){
        $this->code_msg = array(
            '0' => '成功',
            '1' => '失败',
            '2' => '必选项不能为空',
            '3' => '已经存在',
            '4' => '不存在',
            '5' => '不匹配',
            '11'=> '非GET请求',
            '12'=> '非POST请求',
            '999'=>'系统忙'
        );
        $this->result = array(
            'code' => '999',
            'count' => 0,
            'data' => array(),
            'msg' => $this->code_msg['999']
        );
    }
    /**
     * 数据列表
     * $tableName param string 表名
     * $Fields param string|array 字段名
     * $relevance param string 父级id的字段名
     * $table param string 附属表
     * $k param string 主表与附属表主键id进行关联的字段
     * $getFields param string|array 附属表获取字段
     * $order param string 排序
     * return json
     */
    public function dataList($tableName , $Fields = FALSE , $relevance = FALSE , $table=FALSE, $k=FALSE , $getFields=FALSE,$order='id DESC'){
        $request = Request::instance();
        if($request->isGet()){
            $param = $request->param();
            if (empty($param['page'])) {
                $page = 1; // 默认
            } else {
                $page = $param['page'];
            }
            if (empty($param['limit'])) {
                $limit = 10; // 默认
            } else {
                $limit = $param['limit'];
            }
            if($relevance) {
                //特例处理的
                if($tableName == 'school_class'){
                    $where1 = '';
                    $where2 = '';
                    $where3 = '';
                    if ($Fields) {
                        $data = $request->only($Fields);
                        foreach ($data as $key => $value) {
                            if ($value) {
                                if($key == 'name')
                                {
                                    $where1 .= " instr(" . $key . ", '" . $value . "')>0 AND"; // 模糊查询，比like速度快
                                }elseif ($key == 'level_name'){
                                    $key = 'name';
                                    $where2 .= " instr(" . $key . ", '" . $value . "')>0 AND"; // 模糊查询，比like速度快
                                }elseif ($key == 'school_id'){
                                    $where3 .= " instr(" . $key . ", '" . $value . "')>0 AND"; // 模糊查询，比like速度快
                                }

                            }
                        }
                    }
                    $where1 = substr($where1, 0, strlen($where1) - 3);
                    $where2 = substr($where2, 0, strlen($where2) - 3);
                    $where3 = substr($where2, 0, strlen($where2) - 3);
                    $re = Db::name($tableName)->where($where2)->where($where3)
                        ->where($relevance,0)
                        ->order($order)
                        ->select();
                    for($i=0;$i<count($re);$i++){
                        $array = Db::name($tableName)->where($where1)->where($where3)
                            ->where($relevance,$re[$i]['id'])
                            ->order($order)
                            ->select();
                        for($j=0;$j<count($array);$j++){
                            $arr['id'] = $array[$j]['id'];
                            $arr['name'] = $array[$j]['name'];
                            $arr['level_name'] = $re[$i]['name'];
                            $arr['school_id'] = $array[$j]['school_id'];
                            $arr['level_id'] = $array[$j]['level_id'];
                            $res[] = $arr;
                        }

                    }
                    $count = count($res);
                    if($limit*($page-1)>=$count){
                        $list[] = array();
                    }else{
                        if(($limit*($page-1)+$limit)>$count){
                            $max = $count;
                        }else{
                            $max = $limit*($page-1)+$limit;
                        }
                        for($n=$limit*($page-1);$n<$max;$n++){
                            foreach ($res[$n] as $key=>$v){
                                $ar[$key]=$v;
                            }
                            $list[] = $ar;
                        }
                    }
                }
            }else{
                $where = '';
                if ($Fields) {
                    $data = $request->only($Fields);
                    foreach ($data as $key => $value) {
                        if ($value) {
                            $where .= " instr(" . $key . ", '" . $value . "')>0 AND"; // 模糊查询，比like速度快
                        }
                    }
                }
                $where = substr($where, 0, strlen($where) - 3);
                $list = Db::name($tableName)->where($where)
                    ->field($Fields)
                    ->order($order)
                    ->limit($limit * ($page - 1), $limit)
                    ->select();
                $count = Db::name($tableName)->where($where)
                    ->limit($limit * ($page - 1), $limit)
                    ->count('id');
            }
            if($table){
                foreach ($list as &$value){
                    $value[$table] = Db::name($table)->where('id',$value[$k])->value($getFields);
                }
            }
            $this->result['code'] = 0;
            $this->result['count'] = $count;
            $this->result['data'] = $list;
            $this->result['msg'] = $this->code_msg[$this->result['code']];
            return json_encode($this->result,JSON_UNESCAPED_UNICODE);
        }else{
            $this->result['code'] = 11;
            $this->result['msg'] = $this->code_msg[$this->result['code']];
            return json_encode($this->result,JSON_UNESCAPED_UNICODE);
        }
    }
    public function dataMultiList(){

    }
    /**
     * 添加/修改
     * $tableName param string 表名
     * $Fields param string|array 字段名
     * $Rule param string 验证器类名
     * $relevance param string 父级id的字段名
     * return json
    */
    public function saveData($tableName, $Fields, $Rule=FALSE , $relevance = FALSE){
        $request = Request::instance();
        if ($request->isPost()) {
            $param = $request->param();
            if($Rule){
                $validate = validate($Rule);
                if(!$validate->check($param)){
                    $this->result['code'] = 2;
                    $this->result['msg'] = $validate->getError();
                    return json_encode($this->result,JSON_UNESCAPED_UNICODE);
                }
            }
            $data = $request->only($Fields);
            if(in_array('addtime',$Fields)){
                $data['addtime']=time();
            }
            if(isset($data['password'])){
                $data['password']=md5($data['password']);
            }
            if($relevance) {
                if (!empty($param['id'])) {
                    $states = '修改';
                    //特例处理
                    if($tableName == 'school_class'){
                        //查看年级是否已经存在
                        $grade = Db::name($tableName)->where(array('school_id'=>$data['school_id'],'name'=>$data['parent_name'],'level_id'=>0))->find();
                        if(empty($grade)){
                            $level_id = Db::name($tableName)->insertGetId(array('school_id'=>$data['school_id'],'name'=>$data['parent_name'],'level_id'=>0));
                        }else{
                            $level_id = $grade['id'];
                        }
                        $re = Db::name($tableName)->where('id', $param['id'])->update(array('school_id'=>$data['school_id'],'name'=>$data['name'],'level_id'=>$level_id));
                    }
                } else {
                    $states = '添加';
                    //特例处理
                    if($tableName == 'school_class'){
                        //查看年级是否已经存在
                        $grade = Db::name($tableName)->where(array('school_id'=>$data['school_id'],'name'=>$data['parent_name'],'level_id'=>0))->find();
                        if(empty($grade)){
                            $level_id = Db::name($tableName)->insertGetId(array('school_id'=>$data['school_id'],'name'=>$data['parent_name'],'level_id'=>0));
                        }else{
                            $level_id = $grade['id'];
                        }
                        $re = Db::name($tableName)->insertGetId(array('school_id'=>$data['school_id'],'name'=>$data['name'],'level_id'=>$level_id));
                    }
                }
            }else{
                if (!empty($param['id'])) {
                    $states = '修改';
                    $re = Db::name($tableName)->where('id', $param['id'])->update($data);
                } else {
                    $states = '添加';
                    $re = Db::name($tableName)->insertGetId($data);
                }
            }
            if ($re !== false) {
                $this->result['code'] = 0;
                $this->result['msg'] = $states . '成功';
                $this->result['data'] = array(
                    'id' => $re
                );
            } else {
                $this->result['code'] = 1;
                $this->result['msg'] = $states . '失败';
            }
            unset($this->result['count']);
            return json_encode($this->result,JSON_UNESCAPED_UNICODE);
        } else {
            $this->result['code'] = 12;
            $this->result['msg'] = $this->code_msg[$this->result['code']];
            unset($this->result['count']);
            return json_encode($this->result,JSON_UNESCAPED_UNICODE);
        }
    }
    /**
     * 删除
     * $tableName param string 表名
     * return json
    */
    public function deleteData($tableName){
        $request = Request::instance();
        if ($request->isPost()) {
            $param = $request->param();
            if (empty($param['id'])) {
                $this->result['code'] = 2;
                $this->result['msg'] = $this->code_msg[$this->result['code']];
            } else {
                if (Db::name($tableName)->where('id', $param['id'])->find()) {
                    $re = Db::name($tableName)->delete($param['id']);
                    if ($re) {
                        $this->result['code'] = 0;
                        $this->result['msg'] = $this->code_msg[$this->result['code']];
                    } else {
                        $this->result['code'] = 1;
                        $this->result['msg'] = $this->code_msg[$this->result['code']];
                    }
                } else {
                    $this->result['code'] = 5;
                    $this->result['msg'] = $this->code_msg[$this->result['code']];
                }
            }
        } else {
            $this->result['code'] = 12;
            $this->result['msg'] = $this->code_msg[$this->result['code']];
        }
        unset($this->result['count']);
        return json_encode($this->result,JSON_UNESCAPED_UNICODE);
    }
}